<template>
  <div class="im-answer bg-fff border-top fixed-bottom">
    <div class="answer-huid pl-30 border-bottom ">
      <textarea  class="aninput-tex f32 fl my-20" placeholder="点击输入您的问题" v-model="msgToSent" @keyup.enter="sendTextMsg" @focus="focusInput"></textarea>
      <a class="huid-add mr-30 fr " v-if="!msgToSent && !fileControlShow" @click="showFileControl"></a>
      <a class="huid-close mr-30 fr " v-else-if="!msgToSent && fileControlShow" @click="showFileControl"></a>
      <a class="send-out f32 color-fff text-center fr" v-else  @click="sendTextMsg">发送</a>
    </div>
    <div class="answer-function py-30" v-show="fileControlShow">
      <div class="funlist fl text-center" v-if="type==='session' && !isRobot" @change="sendFileMsg" >
        <i class="album" ></i>
        <p class="f32 color-666 mt-10">相册</p>
        <input class="funfile" type="file" ref="fileToSent" >
      </div>
      <div class="funlist fl text-center" v-if="type==='session' && !isRobot" @change="sendFileMsgCamera">
        <i class="ptgraph"></i>
        <p class="f32 color-666 mt-10">拍照</p>
        <input class="funfile" type="file" accept="image/*" ref="fileToSentCamera" >
      </div>
    </div>
  </div>
</template>

<script>
import ChatEmoji from './ChatEmoji'
import util from 'js/utils'
import pageUtil from 'js/utils/page'
import config from '../config'

export default {
  components: {
    ChatEmoji
  },
  updated () {
    window.document.body.addEventListener('click', () => {
      this.isEmojiShown = false
    })
  },
  props: {
    type: String,
    scene: String,
    to: String,
    isRobot: {
      type: Boolean,
      default () {
        return false
      }
    }
  },
  watch: {
    continueRobotAccid (curVal, oldVal) {
      if (curVal && this.robotInfos[curVal]) {
        this.msgToSent = `@${this.robotInfos[curVal].nick} `
      }
      // 重置
      this.$store.dispatch('continueRobotMsg', '')
    },
    msgToSent (curVal, oldVal) {
      if (this.type === 'chatroom' || this.isRobot) {
        return
      }
      let indexAt = this.msgToSent.indexOf('@')
      if (indexAt >= 0 && (indexAt === this.msgToSent.length - 1)) {
        if (this.robotslist && this.robotslist.length > 0) {
          this.isRobotListShown = true
        }
      } else if (this.isRobotListShown === true) {
        this.isRobotListShown = false
      }
    }
  },
  data () {
    return {
      isEmojiShown: false,
      isRobotListShown: false,
      fileControlShow: false,
      msgToSent: '',
      icon1: `${config.resourceUrl}/im/chat-editor-1.png`,
      icon2: `${config.resourceUrl}/im/chat-editor-2.png`,
      icon3: `${config.resourceUrl}/im/chat-editor-3.png`,
    }
  },
  computed: {
    continueRobotAccid () {
      return this.$store.state.im.continueRobotAccid
    },
    robotslist () {
      return this.$store.state.im.robotslist
    },
    robotInfos () {
      return this.$store.state.im.robotInfos
    },
    robotInfosByNick () {
      return this.$store.state.im.robotInfosByNick
    }
  },
  methods: {
    focusInput(){
      this.fileControlShow=false
    },
    showFileControl() {
      this.fileControlShow = !this.fileControlShow
    },
    sendTextMsg () {
      if (/^\s*$/.test(this.msgToSent)) {
        this.$vux.alert.show({
          title: '请不要刷屏'
        })
        return
      } else if (this.msgToSent.length > 800) {
        this.$vux.alert.show({
          title: '请不要超过800个字'
        })
        return
      }
      this.msgToSent = this.msgToSent.trim()
      if (this.type === 'session') {
        // 如果是机器人
        if (this.isRobot) {
          this.$store.dispatch('sendRobotMsg', {
            type: 'text',
            scene: this.scene,
            to: this.to,
            robotAccid: this.to,
            // 机器人后台消息
            content: this.msgToSent,
            // 显示的文本消息
            body: this.msgToSent
          })
        } else {
          let robotAccid = ''
          let robotText = ''

          let atUsers = this.msgToSent.match(/@[^\s@$]+/g)
          if (atUsers) {
            for (let i = 0; i < atUsers.length; i++) {
              let item = atUsers[i].replace('@', '')
              if (this.robotInfosByNick[item]) {
                robotAccid = this.robotInfosByNick[item].account
                robotText = (this.msgToSent + '').replace(atUsers[i], '').trim()
                break
              }
            }
          }
          if (robotAccid) {
            if (robotText) {
              this.$store.dispatch('sendRobotMsg', {
                type: 'text',
                scene: this.scene,
                to: this.to,
                robotAccid,
                // 机器人后台消息
                content: robotText,
                // 显示的文本消息
                body: this.msgToSent
              })
            } else {
              this.$store.dispatch('sendRobotMsg', {
                type: 'welcome',
                scene: this.scene,
                to: this.to,
                robotAccid,
                // 显示的文本消息
                body: this.msgToSent
              })
            }
          } else {
            let obj,expand;
            if(this.$isLocalStorageSupported() && localStorage.getItem('imOrderInfo')){
              obj=JSON.parse(localStorage.getItem('imOrderInfo'))
              expand={
                orderId:obj.orderInfo.OrderId,
                rcId:obj.orderInfo.CustomServiceLoginId,
                userType:obj.userType,
                clientType:'M10.1'
              }
            }
            //test
            /*let expand= '{"orderId":"DB20170510377726330","rcId":"担保客服组长5","userType":"seller","clientType":"M10.1"}'
            expand=JSON.parse(expand)*/
            //console.log(expand)
            this.$store.dispatch('sendMsg', {
              type: 'text',
              scene: this.scene,
              to: this.to,
              custom:JSON.stringify(expand),
              text: this.msgToSent
            })
            //pageUtil.scrollChatListDown()
          }
        }
      } else if (this.type === 'chatroom') {
        this.$store.dispatch('sendChatroomMsg', {
          type: 'text',
          text: this.msgToSent
        })
      }
      this.msgToSent = ''
    },
    sendPlayMsg () {
      // 发送猜拳消息
      if (this.type === 'session') {
        this.$store.dispatch('sendMsg', {
          type: 'custom',
          scene: this.scene,
          to: this.to,
          pushContent: '[猜拳]',
          content: {
            type: 1,
            data: {
              value: Math.ceil(Math.random()*3)
            }
          }
        })
      } else if (this.type === 'chatroom') {
        this.$store.dispatch('sendChatroomMsg', {
          type: 'custom',
          pushContent: '[猜拳]',
          content: {
            type: 1,
            data: {
              value: Math.ceil(Math.random()*3)
            }
          }
        })
      }
    },
    sendFileMsg () {
      let obj,expand;
      if(this.$isLocalStorageSupported() && localStorage.getItem('imOrderInfo')){
        obj=JSON.parse(localStorage.getItem('imOrderInfo'))
        expand={
          orderId:obj.orderInfo.OrderId,
          rcId:obj.orderInfo.CustomServiceLoginId,
          userType:obj.userType,
          clientType:'M10.1'
        }
      }
      let ipt = this.$refs.fileToSent
      if (ipt.value) {
        if (this.type === 'session') {
          this.$store.dispatch('sendFileMsg', {
            scene: this.scene,
            to: this.to,
            fileInput: ipt,
            custom:JSON.stringify(expand),
          })
          this.fileControlShow=false
        } else if (this.type === 'chatroom') {
          this.$store.dispatch('sendChatroomFileMsg', {
            fileInput: ipt
          })
        }
      }
    },
    sendFileMsgCamera () {
      let obj,expand;
      if(this.$isLocalStorageSupported() && localStorage.getItem('imOrderInfo')){
        obj=JSON.parse(localStorage.getItem('imOrderInfo'))
        expand={
          orderId:obj.orderInfo.OrderId,
          rcId:obj.orderInfo.CustomServiceLoginId,
          userType:obj.userType,
          clientType:'M10.1'
        }
      }
      let ipt = this.$refs.fileToSentCamera
      if (ipt.value) {
        if (this.type === 'session') {
          this.$store.dispatch('sendFileMsg', {
            scene: this.scene,
            to: this.to,
            fileInput: ipt,
            custom:JSON.stringify(expand),
          })
          this.fileControlShow=false
          //pageUtil.scrollChatListDown()
        } else if (this.type === 'chatroom') {
          this.$store.dispatch('sendChatroomFileMsg', {
            fileInput: ipt
          })
        }
      }
    },
    showEmoji () {
      this.isEmojiShown = true
    },
    hideEmoji () {
      this.isEmojiShown = false
    },
    addEmoji (emojiName) {
      this.msgToSent += emojiName
      this.hideEmoji()
    },
    chooseRobot (robot) {
      if (robot && robot.account) {
        let len = this.msgToSent.length
        if (len === 0 || this.msgToSent[len-1] !== '@') {
          this.msgToSent += '@' + robot.nick + ' '
        } {
          this.msgToSent += robot.nick + ' '
        }
      }
    },
    hideRobotList () {
      this.isRobotListShown = false
    }
  }
}
</script>

<style scoped>
  .robot.m-chat-editor-main {
    .u-editor-input {
      padding-right: 4.5rem;
    }
    .u-editor-icons {
      width: 4rem;
    }
  }
  .m-chat-robot {
    overflow-y: scroll;
    .weui-cells {
      .weui-cell__hd {
        margin-right: 0.5rem;
      }
    }
  }
</style>
<style  src="css/member/member-im.css"></style>
